package com.taoyeshu.modules.sys.controller;

import java.awt.image.BufferedImage;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.taoyeshu.common.utils.CaptchaUtil;
import com.taoyeshu.common.web.BaseController;
import com.taoyeshu.modules.sys.entity.User;

/**
 * 
 * @描述:登录
 * @作者 :HuanGe
 * @创建日期 :2015年6月5日 下午4:22:10
 *
 */
@Controller
@RequestMapping("/")
public class LoginController extends BaseController {

	@RequestMapping("/login")
	public String login(Model model, ModelMap modelMap) throws Exception {
		return "/modules/sys/login";
	}

	@RequestMapping(value = "/login.json", method = { RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> login(@Validated User user, BindingResult bindingResult, HttpServletRequest request,
			HttpServletResponse response, RedirectAttributes redirectAttributes) {
		String captcha = request.getParameter("captcha");
		String validateCode = (String) request.getSession().getAttribute(CaptchaUtil.KEY_CAPTCHA);
		Map<String, Object> modelMap = new HashMap<String, Object>();
		if (StringUtils.isNotBlank(captcha) && captcha.equals(validateCode)) {
			try {
				if (bindingResult.hasErrors()) {
					modelMap.put("success", false);
					modelMap.put("message", "用户名或密码错误！");
					return modelMap;
				}
				UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
				SecurityUtils.getSubject().login(token);
				token.clear();
				modelMap.put("success", true);
				return modelMap;
			} catch (AuthenticationException e) {
				modelMap.put("success", false);
				modelMap.put("message", "用户名或密码错误！");
				return modelMap;
			}
		} else {
			modelMap.put("success", false);
			modelMap.put("message", "验证码错误！");
			return modelMap;
		}
	}

	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public String logout(RedirectAttributes redirectAttributes) {
		// 使用权限管理工具进行用户的退出，跳出登录，给出提示信息
		SecurityUtils.getSubject().logout();
		redirectAttributes.addFlashAttribute("message", "您已安全退出");
		return "redirect:/login";
	}

	@RequestMapping("/403")
	public String unauthorizedRole() {
		return "/403";
	}

	/**
	 * 
	 * @描述:登录验证码
	 * @方法名称 :getImage
	 * @作者 :HuanGe
	 * @创建日期 :2015年6月6日 上午12:23:00
	 * @param request
	 * @param response
	 *
	 */
	@RequestMapping(value = "/getCaptcha")
	public void getImage(HttpServletRequest request, HttpServletResponse response) {
		response.setContentType("image/jpeg");
		// 不缓存此内容
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expire", 0);
		try {

			HttpSession session = request.getSession();

			CaptchaUtil tool = new CaptchaUtil();
			StringBuffer code = new StringBuffer();
			BufferedImage image = tool.genRandomCodeImage(code);
			session.removeAttribute(CaptchaUtil.KEY_CAPTCHA);
			session.setAttribute(CaptchaUtil.KEY_CAPTCHA, code.toString());

			// 将内存中的图片通过流动形式输出到客户端
			ImageIO.write(image, "JPEG", response.getOutputStream());

		} catch (Exception e) {
		}
	}

}
